-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.c
61 lines (50 loc) · 1.38 KB
/
Solution.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <limits.h>
#define MAX 100
int findMinDistance(int dist[], int visited[], int n) {
int min = INT_MAX, minIndex = -1;
for (int v = 0; v < n; v++) {
if (!visited[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
void dijkstra(int graph[MAX][MAX], int n, int start) {
int dist[n], visited[n];
for (int i = 0; i < n; i++) {
dist[i] = INT_MAX;
visited[i] = 0;
}
dist[start] = 0;
for (int count = 0; count < n - 1; count++) {
int u = findMinDistance(dist, visited, n);
visited[u] = 1;
for (int v = 0; v < n; v++) {
if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printf("Vertex\tDistance from Source\n");
for (int i = 0; i < n; i++) {
printf("%d\t%d\n", i, dist[i]);
}
}
int main() {
int n, start;
int graph[MAX][MAX];
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting vertex: ");
scanf("%d", &start);
dijkstra(graph, n, start);
return 0;
}